package com.wangsd.common.component;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import com.wangsd.web.coupon.entity.ServiceBusiness;
import com.wangsd.web.coupon.service.ServiceBusinessService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WeixinPayService {
    @Value("${wx.pay.appId}")
    private String payAppId;//微信支付服务商公众号id
    @Value("${wx.pay.mchId}")
    private String payMchId;//微信支付服务商商户号
    @Value("${wx.pay.mchKey}")
    private String payMchKey;//微信支付服务商秘钥
    @Value("${wx.pay.keyPath}")
    private String keyPath;//微信支付服务商证书

    @Autowired
    ServiceBusinessService serviceBusinessService;

    private static Map<String, WxPayService> mpServices = Maps.newHashMap();


    public WxPayService getPayService(String code, String subMchId) {
        if (code != null) {
            ServiceBusiness business = serviceBusinessService.selectBusinessByCode(code);
            payMchId = business.getMchId();
            payMchKey = business.getMchKey();
            payAppId = business.getAppId();
            keyPath = business.getKeyPath();
        }

        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(payMchId);
        payConfig.setMchId(payAppId);
        payConfig.setMchKey(payMchKey);
        payConfig.setKeyPath(keyPath);

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        if (subMchId != null) {
            payConfig.setSubMchId(subMchId);
        }

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

}
